package com.zhentao.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.common.dtos.ResponseResult;
import com.zhentao.config.WxMaServiceConfig;
import com.zhentao.config.WxMaServiceConfigProperties;
import com.zhentao.mapper.AppUserInfoMapper;
import com.zhentao.mapper.AppUserMapper;
import com.zhentao.service.UserLoginService;
import com.zhentao.user.domain.AppUser;
import com.zhentao.user.dto.UserDto;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@EnableConfigurationProperties(WxMaServiceConfigProperties.class)
@Import(WxMaServiceConfig.class)
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private  AppUserMapper appUserMapper;
    @Autowired
    private  AppUserInfoMapper appInfoMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;


    private final WxMaService wxMaService;





    @SneakyThrows
    @Override
    public ResponseResult miniApplogin(UserDto dto) {
        if(StringUtils.isBlank(dto.getCode())){
            return ResponseResult.errorResult(400,"参数不能为空");
        }
        WxMaJscode2SessionResult session;
        try {
            //获取openId
            session = wxMaService.getUserService().getSessionInfo(dto.getCode());
            String openid = session.getOpenid();
            //获取手机号
//            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(phoneCode);
//            String phoneNumber = phoneNoInfo.getPhoneNumber();

            //用户第一次登录就是注册
            AppUser user = appUserMapper.selectOne(Wrappers.<AppUser>lambdaQuery().eq(AppUser::getOpenId, openid));
            if(ObjUtil.isEmpty(user)){
                //直接注册
                AppUser appUser=new AppUser();
                appUser.setOpenId(openid);
//                appUser.setPhone(phoneNumber);
                appUser.setIsAuthentication(2);
                appUser.setStatus(1);
                appUser.setNickname(dto.getNickName());
                appUser.setAvatar(dto.getAvatarUrl());
                appUser.setLastLoginTime(new Date());
                appUserMapper.insert(appUser);
                redisTemplate.opsForValue().set("login:"+ openid, JSON.toJSONString(appUser));
            }else {
//                更新用户信息
                user.setAvatar(dto.getAvatarUrl());
                user.setNickname(dto.getNickName());
                user.setLastLoginTime(new Date());
                appUserMapper.updateById(user);
                redisTemplate.opsForValue().set("login:"+ openid, JSON.toJSONString(user));
            }
            return ResponseResult.okResult(openid);
        }catch (WxErrorException e){
            log.error(e.getMessage(), e);
            return ResponseResult.errorResult(500,e.toString());
        }finally {
            WxMaConfigHolder.remove();
        }
    }

//    @Override
//    public ResponseResult miniAppLogin1(UserDto dto) {
//        WxMaJscode2SessionResult session;
//        try {
//            //获取openId
//            session = wxMaService.getUserService().getSessionInfo(dto.getCode());
//            String openid = session.getOpenid();
//            return ResponseResult.okResult(openid);
//        }catch (WxErrorException e){
//            log.error(e.getMessage(), e);
//            return ResponseResult.errorResult(500,e.toString());
//        }
//        finally {
//            WxMaConfigHolder.remove();
//        }
//    }


}
